<template>
    <div class="container create">
        <!-- 回到顶部 -->
        <el-backtop :right="100" :bottom="100" ref="backTop" target=".el-main" />
        <div class="form box">
            <h4>商品(Spu)介绍</h4>
            <el-form ref="ruleFormRef" @submit.native.prevent scroll-to-error :model="ruleForm" :rules="rules"
                label-width="120px" class="demo-ruleForm" status-icon>
                <el-form-item label="商品名称" prop="title">
                    <el-input v-model="ruleForm.title" />
                </el-form-item>
                <el-form-item label="原始价格" prop="originalPrice">
                    <el-input type="number" v-model="ruleForm.originalPrice" placeholder="请输入原始价格" @input="checknum(1)">
                        <template #append>元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="当前价格" prop="price">
                    <el-input type="number" v-model="ruleForm.price" placeholder="请输入当前价格" @input="checknum(1)">
                        <template #append>元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="VIP价格" prop="vipPrice">
                    <el-input type="number" v-model="ruleForm.vipPrice" placeholder="请输入VIP价格" @input="checknum(1)">
                        <template #append>元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="剩余库存">
                    <el-input v-model.number="ruleForm.stock" />
                </el-form-item>
                <el-form-item label="运费模板" prop="region">
                    <el-select v-model="ruleForm.freightTemplateId" placeholder="请选择运费模板">
                        <el-option v-for="item in freight" :key="item.id" :label="item.title" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="是否在售" prop="status">
                    <el-radio-group v-model="ruleForm.status">
                        <el-radio label=1>在售</el-radio>
                        <el-radio label=0>下架</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="商品图片">
                    <el-upload ref="uploadRef" :limit="5" :on-exceed="handlePictureCardExceed" :headers="headers"
                        :action="uploadPath" list-type="picture-card" :on-success="handleAvatarSuccess"
                        :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="商品单位" prop="unit">
                    <el-input v-model="ruleForm.unit" placeholder="件/个/盒" />
                </el-form-item>
                <el-form-item label="所属类目" prop="region">
                    <el-cascader placeholder="请选择所属类目"
                        :props="{ emitPath: false, value: 'id', children: 'childrenList', label: 'title' }"
                        v-model="ruleForm.categoryId" :options="cascaderCategoryData" />
                </el-form-item>
                <el-form-item label="商品简介">
                    <el-input v-model="ruleForm.description" />
                </el-form-item>
                <el-form-item label="商品详细介绍" prop="detail">
                    <RichText @blur="checkRichText" style="width: 100%;height: 200px;" v-model="ruleForm.detail"
                        :languageValue="languageValue" @getContent="getContent" />
                </el-form-item>
            </el-form>
        </div>
        <div class="skuDetail box">
            <h4>商品参数</h4>
            <div class="box-content">
                <el-tag @click="openSetDiaglo(1)">添加</el-tag>
                <div class="box-content-table">
                    <el-table :data="ruleForm.attributeList" style="width: 100%">
                        <el-table-column prop="attribute" label="商品参数名称" align="center" />
                        <el-table-column prop="value" label="商品参数值" align="center" />
                        <el-table-column label="操作" align="center">
                            <template #default="scope">
                                <el-button size="small" type="primary" icon="delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <div class="skuDetail box">
            <h4>规格维度</h4>
            <div class="box-content">
                <el-tag @click="openSetDiaglo(2)">添加</el-tag>
                <div class="box-content-table">
                    <el-table :data="ruleForm.specificationList" style="width: 100%">
                        <el-table-column prop="id" label="维度Id" align="center" />
                        <el-table-column prop="title" label="维度名称" align="center" />
                        <el-table-column prop="gmtCreate" label="创建时间" align="center" />
                        <el-table-column label="操作" align="center">
                            <template #default="scope">
                                <el-button size="small" type="primary" icon="delete"
                                    @click="handleDeleteTitle(scope.$index)">删除</el-button>
                                <el-button size="small" type="danger" icon="edit"
                                    @click="handleEditTitle(scope.row.title, scope.$index)">修改</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <div class="skuDetail box">
            <h4>商品(Sku)详情</h4>
            <div class="box-content">
                <el-button type="primary" style="margin-bottom: 20px;width: 80px;" @click="openSetDiaglo(3)"
                    :disabled="ruleForm.skuList.length === 0" plain>批量定价</el-button>
                <div class="skuList">
                    <div class="skuList-item" v-for="(item, index) in ruleForm.specificationList" :key="index">
                        <el-tag class="ml-2" type="warning">{{ item.title }}</el-tag>
                        <el-tag class="ml-2" closable @close="handleClose(index, indexs)" type="success"
                            v-for="(items, indexs) in item.values" :key="index">{{ items
                            }}</el-tag>
                        <el-button class="button-new-tag ml-1">
                            <el-input v-model="item.inputValue" @blur="handleAddValuesItem(item)"
                                @keyup.enter="handleAddValuesItem(item)" v-if="item.inputSkuTagVisible" />
                            <div v-else @click="item.inputSkuTagVisible = true">+ 添加</div>
                        </el-button>
                    </div>
                </div>
                <div class="box-content-table">
                    <el-table :data="ruleForm.skuList" style="width: 100%" border :span-method="spanMethod">
                        <el-table-column align="center" width="100pxx"
                            v-for="(item, index) in ruleForm.specificationList.filter((v) => v.values.length)"
                            :prop="'id_' + item.title" :label="item.title">
                        </el-table-column>
                        <el-table-column prop="spuId" label="skuId" align="center" width="115px" />
                        <el-table-column prop="originalPrice" label="￥价格(元)" align="center" width="180px">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.originalPrice" :min="1" @change="handleChange" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="vipPrice" label="￥VIP价(元)" align="center" width="180px">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.vipPrice" :min="1" @change="handleChange" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="price" label="￥吊牌价(元)" align="center" width="180px">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.price" :min="1" @change="handleChange" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="stock" label="库存(件)" align="center" width="180px">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.stock" :min="0" @change="handleChange" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="weight" label="重量(克)" align="center" width="180px">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.weight" :min="0" @change="handleChange" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="img" label="SKU图片" align="center" width="100">
                            <template #default="scope">
                                <el-upload class="uploader" :headers="headers" :action="uploadPath" :show-file-list="false"
                                    :on-success="handleAvatarSuccess1" :before-upload="beforeAvatarUpload">
                                    <div @click="getUrlInddex(scope.$index)">
                                        <div class="sku-img" v-if="scope.row.img">
                                            <img :src="scope.row.img" class="skuImg" />
                                        </div>
                                        <el-icon v-else class="uploader-icon">
                                            <Upload />
                                        </el-icon>
                                    </div>
                                </el-upload>
                            </template>
                        </el-table-column>
                        <el-table-column prop="barCode" label="条形码" width="190px" align="center">
                            <template #default="scope">
                                <el-input v-model="scope.row.barCode">
                                    <template #append>
                                        <div @click="getBarCode(scope.row)">随机</div>
                                    </template>
                                </el-input>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <div class="button">
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                创建
            </el-button>
        </div>
        <!-- 查看图片 -->
        <el-dialog v-model="dialogVisible" width="700px">
            <img :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
        <!-- 设置商品对话框 -->
        <el-dialog v-model="setDialog" width="500px" :title="setTitle" @close="closeSetDialog">
            <div v-if="setValue === 1">
                <el-form ref="ruleFormRef1" :rules="form1Rules" :model="form1" :label-width="formLabelWidth">
                    <el-form-item label="商品参数名称" prop="name">
                        <el-input v-model="form1.name" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="商品参数值" prop="value">
                        <el-input v-model="form1.value" autocomplete="off" />
                    </el-form-item>
                </el-form>
            </div>
            <div v-if="setValue === 2">
                <el-form ref="ruleFormRef2" @submit.native.prevent :rules="form2Rules" :model="form2"
                    :label-width="formLabelWidth">
                    <el-form-item label="类型名称" prop="name">
                        <el-input v-model="form2.name" autocomplete="off" />
                    </el-form-item>
                </el-form>
            </div>
            <div v-if="setValue === 3">
                <el-form ref="ruleFormRef3" :rules="form3Rules" :model="form3" label-width="180">
                    <el-form-item label="现价(￥)" prop="price">
                        <el-input-number v-model="form3.price" :min="1" @input="checknum(0)" />
                    </el-form-item>
                    <el-form-item label="VIP价格(￥)" prop="vipPrice">
                        <el-input-number v-model="form3.vipPrice" :min="1" @input="checknum(0)" />
                    </el-form-item>
                    <el-form-item label="吊牌价(￥)" prop="originalPrice">
                        <el-input-number v-model="form3.originalPrice" :min="1" @input="checknum(0)" />
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closeSetDialog()">取消</el-button>
                    <el-button type="primary" @click="submitForm1(ruleFormRef1)" v-if="setValue === 1">
                        确定
                    </el-button>
                    <el-button type="primary" @click="submitForm2(ruleFormRef2)" v-if="setValue === 2">
                        确定
                    </el-button>
                    <el-button type="primary" @click="submitForm3(3)" v-if="setValue === 3">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 创建成功 -->
        <el-dialog v-model="successDialog" title="创建成功" width="30%" align-center>
            <span>商品创建成功,是否继续添加商品</span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="successTo(0)" type="primary" plain>关闭</el-button>
                    <el-button type="primary" @click="successTo(1)">
                        继续
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch, nextTick } from 'vue'
import { ClassCreateFrom, ClassSku, ClassSpecification } from "#/index";
import { get, post, uploadPath } from '@/utils/https'
import { ElMessage } from 'element-plus/lib/components/index.js'
import type { UploadProps, FormInstance, UploadInstance, FormRules } from 'element-plus/lib/components/index.js'
import RichText from '../../components/richtext/RichText.vue'
import cookie from "js-cookie";
import { useRouter } from 'vue-router'
import { useStoreTags } from '../../stores/tags/index'
const store = useStoreTags()
const router = useRouter()

let languageValue = computed(() => {
    return localStorage.getItem('locale')
})//切换富文本语言
let backTop = ref()//表格回到顶部绑定的数据
let cascaderCategoryData: TypeSpuBigTree[] = reactive([])
let freight: TypeFreight[] = reactive([])
let dialogImageUrl = ref('')
let successDialog = ref(false)//设置参数对话框
let dialogVisible = ref(false)//查看图片对话框
let setDialog = ref(false)//设置参数对话框
let SetTitleIndex = 0//修改的规格维度下标
let setTitle = ref('设置商品参数')
let setValue = ref(3)
let formLabelWidth = '120px'
let uploadRef = ref<UploadInstance>()//图片
// 表单数据
let ruleForm = reactive(new ClassCreateFrom())
const ruleFormRef = ref<FormInstance>()
const ruleFormRef1 = ref<FormInstance>()
const ruleFormRef2 = ref<FormInstance>()
const ruleFormRef3 = ref<FormInstance>()
const form1 = reactive({
    name: '',
    value: '',
})
const form2 = reactive({
    name: '',
})
const form3 = reactive({
    originalPrice: 0,
    price: 0,
    vipPrice: 0
})
// 表单验证定义值
const rules = reactive<FormRules>({
    title: [{ required: true, message: '商品名称不能为空', trigger: ['blur', 'change'] }],
    originalPrice: [
        { validator: price2, trigger: ['blur', 'change'] },
        { validator: price, trigger: ['blur', 'change'] },
        { required: true, message: '请输入原始价格', trigger: 'blur' },
        // { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正确原始价格' }
    ],
    price: [
        { validator: price1, trigger: ['blur', 'change'] },
        { validator: price, trigger: ['blur', 'change'] },
        { required: true, message: '请输入当前价格', trigger: 'blur' },
        // { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正确价格' }
    ],
    vipPrice: [
        { validator: price3, trigger: ['blur', 'change'] },
        { validator: price, trigger: ['blur', 'change'] },
        { required: true, message: '请输入VIP价格', trigger: 'blur' },
        // { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正确VIP价格' }
    ],
    status: [{ required: true, message: '请选择商品状态', trigger: ['blur', 'change'] }],
    unit: [{ required: true, validator: unit, trigger: ['blur', 'change'] }],
    detail: [{ required: true, message: '请输入商品详情', trigger: ['blur', 'change'] }],
})
const checkRichText = () => {
    ruleFormRef.value?.validateField(['detail'], (valid: any) => null)
}
/**单位验证 */
function unit(rule: string, value: string, callback: Function) {
    if (value == '') {
        callback(new Error('请输入商品单位'))
    } else if (value != '件' && value != '个' && value != '盒') {
        callback(new Error('请输入正确的单位格式'))
    } else {
        callback()
    }
}
/**价格验证 */
function price(rule: string, value: number, callback: Function) {
    value = Number(value)
    if (value <= 0) {
        callback(new Error('价格不能少于0元'))
    } else {
        callback()
    }
}
function price1(rule: string, value: number, callback: Function) {
    // console.log(value, 'value');
    value = Number(value)
    if (value >= ruleForm.originalPrice) {
        callback(new Error('当前价格不能大于原始价格'))
    } else if (value < ruleForm.vipPrice) {
        callback(new Error('当前价格不能少于VIP价格'))
    } else {
        callback()
    }
}
function price2(rule: string, value: number, callback: Function) {
    // console.log(value, 'value');
    value = Number(value)
    if (value <= ruleForm.price) {
        callback(new Error('原始价格不能少于当前价格'))
    } else if (value <= ruleForm.vipPrice) {
        callback(new Error('原始价格不能少于VIP价格'))
    } else {
        callback()
    }
}
function price3(rule: string, value: number, callback: Function) {
    value = Number(value)
    if (value >= ruleForm.originalPrice) {
        callback(new Error('VIP价格不能多于原始价格'))
    } else if (value > ruleForm.price) {
        callback(new Error('VIP价格不能多于当前价格'))
    } else {
        callback()
    }
}
const form1Rules = reactive<FormRules>({
    name: [{ required: true, message: '商品参数名称不能为空', trigger: 'change' }],
    value: [{ required: true, message: '商品参数值不能为空', trigger: 'change' }],
})
const form2Rules = reactive<FormRules>({
    name: [{ required: true, message: '类型名称不能为空', trigger: 'change' }],
})
const form3Rules = reactive<FormRules>({
    price: [{ validator: formPrice1, trigger: ['blur', 'change'] }],
    vipPrice: [{ validator: formPrice2, trigger: ['blur', 'change'] }],
    originalPrice: [{ validator: formPrice3, trigger: ['blur', 'change'] }],
})
function formPrice1(rule: string, value: number, callback: Function) {
    value = Number(value)
    // console.log('验证现价');
    if (value >= form3.originalPrice) {
        callback(new Error('现价不能多于吊牌价'))
    } else if (value < form3.vipPrice) {
        callback(new Error('现价不能少于VIP价格'))
    } else {
        callback()
    }
}
function formPrice2(rule: string, value: number, callback: Function) {
    value = Number(value)
    if (value >= form3.originalPrice) {
        callback(new Error('VIP价格不能多于吊牌价'))
    } else if (value > form3.price) {
        callback(new Error('VIP价格不能多于现价'))
    } else {
        callback()
    }
}
function formPrice3(rule: string, value: number, callback: Function) {
    value = Number(value)
    if (value <= form3.vipPrice) {
        callback(new Error('吊牌价不能少于vip价格'))
    } else if (value <= form3.price) {
        callback(new Error('吊牌价不能少于现价'))
    } else {
        callback()
    }
}
function checknum(n: number) {
    if (n) {
        if (ruleForm.originalPrice) {
            ruleFormRef.value?.validateField(['originalPrice'], (valid: any) => null)
        }
        if (ruleForm.price) {
            ruleFormRef.value?.validateField(['price'], (valid: any) => null)
        }
        if (ruleForm.vipPrice) {
            ruleFormRef.value?.validateField(['vipPrice'], (valid: any) => null)
        }
    } else {
        ruleFormRef3.value?.validateField(['originalPrice', 'price', 'vipPrice'], (valid: any) => null)
    }
}
// 表单验证提交
const submitForm1 = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid: any) => {
        if (valid) {
            console.log('submit!')
            ruleForm.attributeList.push({
                attribute: form1.name,
                value: form1.value
            })
            ruleFormRef1.value!.resetFields()
            setDialog.value = false
        } else {
            //   ElMessage.error("信息不能为空");

        }
    })
}
const submitForm2 = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid: any) => {
        if (valid) {
            //过滤相同参数
            let isExist = true
            ruleForm.specificationList.forEach(item => {
                if (item.title == form2.name) {
                    isExist = false
                    ElMessage.error("规格维度已存在");
                }
            })
            if (setTitle.value == '修改') {
                if (isExist) {
                    ruleForm.specificationList[SetTitleIndex].title = form2.name
                    createSkuTable()
                }
            } else {
                if (isExist) {
                    let id = ruleForm.specificationList.length + 1
                    ruleForm.specificationList.push({
                        id: undefined,
                        title: form2.name,
                        gmtCreate: Date.now(),
                        values: ['111', '222'],
                        inputSkuTagVisible: false,
                        inputValue: ''
                    })
                    ruleFormRef2.value!.resetFields()
                    createSkuTable()
                    ElMessage.success("设置成功");
                }
            }
            setDialog.value = false
        } else {
            console.log('error submit!')
        }
    })
}
// 批量定价
const submitForm3 = (n: number) => {
    // console.log(n);
    console.log(form3, '3');
    const { price, vipPrice, originalPrice } = form3

    ruleForm.skuList.forEach(item => {
        item.price = price
        item.vipPrice = vipPrice
        item.originalPrice = originalPrice
    })
    // ruleFormRef3.value!.resetFields()
    form3.originalPrice = 0
    form3.price = 0
    form3.vipPrice = 0
    setDialog.value = false
}

// 数字输入框绑定事件
const handleChange = (value: number) => {
    // console.log(value, ruleForm.skuList, 'skl')
    // console.log(ruleForm, 'ruleForm')
}
// 打开对话框
const openSetDiaglo = (n: number) => {
    setValue.value = n
    switch (n) {
        case 1:
            setTitle.value = '设置商品参数'
            break;
        case 2:
            setTitle.value = '创建规格'
            break;
        case 3:
            setTitle.value = '批量定价'
            break;
        default:
            break;
    }
    setDialog.value = true
}
// 关闭对话框
const closeSetDialog = () => {
    switch (setValue.value) {
        case 1:
            ruleFormRef1.value!.resetFields()
            break;
        case 2:
            ruleFormRef2.value!.resetFields()
            break;
        case 3:
            ruleFormRef3.value!.resetFields()
            break;
        default:
            break;
    }
    setDialog.value = false
}
// 合并列的方法
const spanMethod = ({ rowIndex, columnIndex }: TypespanMethod) => {
    let specList = ruleForm.specificationList.filter(
        item => item.values.length > 0
    )//获取规格列表
    if (columnIndex < specList.length - 1) {//对要跨行的列进行计算，排除最后一个属性列（最后一个不存在跨行
        let rowSpanNum = 1;//跨行的数量
        for (let i = columnIndex + 1; i < specList.length; i++) {
            rowSpanNum *= specList[i].values.length//跨行的数量=后面属性值数量的成绩
        }
        if (rowIndex % rowSpanNum === 0) {//每次跨行的数量相同，所以当前行索引号%跨行数量==0就是要跨行的开始
            return { rowspan: rowSpanNum, colspan: 1 }
        } else {
            return { rowspan: 0, colspan: 0 }
        }
    }
}
// 获取随机码
const getBarCode = (row: { barCode: number, title: string }) => {
    ruleForm.skuList.forEach(item => {
        if (row.title == item.title) {
            item.barCode = String(Date.now())
        }
    })
}
// 删除title
const handleDeleteTitle = (index: number) => {
    console.log(index, 'index');
    ruleForm.specificationList.splice(index, 1)
    createSkuTable()
}
// 编辑title
const handleEditTitle = (title: string, index: number) => {
    SetTitleIndex = index
    setValue.value = 2
    setTitle.value = "修改"
    setDialog.value = true
    form2.name = title
}
// 移除属性
const handleClose = (index: number, indexs: number) => {
    ruleForm.specificationList[index].values.splice(indexs, 1)
    createSkuTable()
}
// 添加ValuesItem
const handleAddValuesItem = (item: ClassSpecification) => {
    var isExist = true
    item.values.forEach(items => {
        if (items == item.inputValue) {
            isExist = false
            ElMessage.error("规格属性已存在");
        }
    })
    if (item.inputValue && isExist) {
        item.values.push(item.inputValue)
    }
    item.inputValue = ''
    item.inputSkuTagVisible = false
    createSkuTable()
}
// 笛卡尔算法构建sku列表
const createSkuTable = () => {
    const specList = ruleForm.specificationList
    const valueList = specList.filter(item => item.values.length).map(item => item.values)
    const titles = specList.filter(item => item.values.length).map(item => item.title)

    if (valueList.length == 0) {//skuList.values数组没有值，就不用进行计算
        ruleForm.skuList = []
        return
    }
    var skuList = valueList.reduce((pre: string[][], next) => {
        var array: string[][] = []
        pre.forEach(item1 => {
            next.forEach(item2 => {
                array.push(item1.concat([item2]))
            })
        })
        return array
    }, [[]])
    const { price, vipPrice, originalPrice } = form3
    // 构建sku表格数据
    var skuTable = skuList.map(item => {
        let obj: any = {
            price: price,
            vipPrice: vipPrice,
            originalPrice: originalPrice,
            stock: 0,
            barCode: '',
            weight: 0,
            img: '',
            title: "",
            titleArray: new Array<string>(),
            specificationArray: new Array<string>(),
            specification: "",
        }
        item.forEach((val, index) => {
            var key = "id_" + titles[index]
            obj[key] = val;
            obj.titleArray.push(val);
            obj.specificationArray.push(titles[index] + "_" + val)
            //==========保留原有相同规格的内容
        })
        obj.title = obj.titleArray.join(',')
        obj.specification = obj.specificationArray.join(',')
        let findItem = ruleForm.skuList.find(item => item.specification === obj.specification)
        if (findItem) {
            return findItem
        }
        let skuObj = new ClassSku()
        Object.assign(skuObj, obj)
        return skuObj
    })
    ruleForm.skuList = skuTable

}

// 富文本信息
const getContent = (v: string) => {
    // ruleForm.detail = v;
    console.log(v, 'v');

};
// 请求头
const headers = computed(() => {
    return {
        ADMINTOKEN: cookie.get("token")
    }
})
// 宣传画廊图片
/**
 * @handleAvatarSuccess 上传成功事件
 */
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response: { url: string },
    uploadFile: any
) => {
    // console.log(response, 6666);
    ruleForm.imgList.push(response.url)
}
/**
 * @handleRemove 移除图片时触发的事件
 * @uploadFile 当前删除的图片对象，
 * @uploadFiles 剩下的图片对象数组，
 */
const handleRemove: UploadProps['onRemove'] = (uploadFile: any, uploadFiles: any) => {
    // console.log(uploadFile, 'uploadFile')
    // console.log('uploadFiles', uploadFiles)
    ruleForm.imgList = uploadFiles
}
/**
 * @handleRemove 查看图片
 * @uploadFile 图片数据
 * @uploadFile.url 查看放大的图片绑定的值
 */
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile: { url: string }) => {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
}
/**
 * 广告图片
 * @beforeAvatarUpload	上传文件之前的钩子
 */
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('图片类型必须是JPG或者PNG!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }
    return true
}

/**
 * 广告图片
 * @handleAvatarSuccess 文件上传成功时的钩子
 */
let rowImgIndex = 0//获取sku图片下标
const getUrlInddex = (index: number) => {
    rowImgIndex = index
}
const handleAvatarSuccess1: UploadProps['onSuccess'] = (
    response: any,
    uploadFile: any
) => {
    // console.log(response, 'response');
    ruleForm.skuList[rowImgIndex].img = response.url
    // console.log(ruleForm.skuList, 'ruleForm.skuList');
}
const handlePictureCardExceed = () => {
    console.log('超出限制');
    ElMessage.warning('最多上传五张图片！')
}


let createFormData = computed(() => {
    // let data = Object.assign({}, { ...ruleForm });
    let data = { ...ruleForm }
    data.img = ruleForm.imgList[0];

    data.originalPrice = data.originalPrice * 100
    data.price = data.price * 100
    data.vipPrice = data.vipPrice * 100
    data.skuList.forEach((item: any) => {
        item.originalPrice = item.originalPrice * 100
        item.price = item.price * 100
        item.vipPrice = item.vipPrice * 100
    })
    console.log(createFormData.value, 'createFormData.value');
    console.log(ruleForm, 'ruleForm.value');
    return {
        _gp: 'admin.product',
        _mt: 'create',
        spuDTO: JSON.stringify(data)
    }
})
/**表单提交事件 */
const submitForm = (formEl: FormInstance | undefined) => {
    // console.log(createFormData, 'createDatcreateFormDataa');
    console.log(ruleForm, 'ruleForm');
    if (!formEl) return
    formEl.validate((valid: any) => {
        if (valid) {
            console.log('submit!')
            post(createFormData.value).then((res: any) => {
                // console.log('创建商品成功！', res)
                // console.log(ruleForm, 'ruleForm');
                if (200 == res.errno) {
                    // 重置表单
                    uploadRef.value!.clearFiles()
                    ruleFormRef.value!.resetFields()
                    Object.assign(ruleForm, new ClassCreateFrom())
                    ruleForm.detail = ''
                    successDialog.value = true
                } else {
                    ElMessage.error(res.errmsg)
                }
            }).catch(err => {
                console.log(err, 'err');
                ElMessage.error(err)
            })
        } else {
            console.log('error submit!')
        }
    })
}
// 创建成功时调用
const successTo = (n: number) => {
    if (n) {//1确认，继续编辑，重置表单
        successDialog.value = false
        nextTick(() => {//回到顶部
            backTop.value.$el.click?.()
        })
    } else {//0取消，回到商品列表
        successDialog.value = false
        store.removeNowTags()
        router.push('/index/shop/list')
    }
}

// 初始化数据
const getInit = () => {
    let categoryData = {
        _gp: 'admin.category',
        _mt: 'categoryTree',
    }
    get(categoryData).then((res: any) => {
        // console.log('类目获取数据成功', res)
        if (200 == res.errno) {
            cascaderCategoryData.length = 0
            cascaderCategoryData.push(...res.data)
        }
    })
    let freightTemplateId = {
        _gp: 'admin.freight',
        _mt: 'list',
    }
    get(freightTemplateId).then((res: any) => {
        // console.log('运费获取数据成功', res)
        if (200 == res.errno) {
            freight.length = 0
            freight.push(...res.data)
        }
    })
}

onMounted(() => {
    getInit()
})
</script>

<style lang="less" scoped>
h4 {
    margin-bottom: 10px;
    line-height: 60px;
    text-indent: 1em;
}

.box {
    border: 1px solid #dddcdc;
    box-shadow: #cecece 0 0 10px 0;
}

.box-content {
    margin: 1em;

    .el-tag {
        padding: 15px;
        margin-bottom: 10px
    }
}

.el-tag {
    margin-right: 5px
}

/**广告图片 */
.create {
    height: 100vh;
    margin: 20px;
}

.avatar-uploader .avatar {
    width: 148px;
    height: 148px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    border: #acaaaa dashed 1px;
    text-align: center;
}

img {
    width: 100%;
    height: 100%;
}

.sku-img img {
    width: 70px;
    height: 70px
}

.button {
    margin: 30px 0;
    height: 70px;

    .el-button {
        float: right;
    }
}

.skuList-item {
    display: flex;

    .skuList-item-values {
        margin: 0px;
        padding: 0px;
        background-color: #8c939d;
    }
}

/deep/ .el-input-group__append {
    width: 40px
}
</style>